<?php
namespace App\Admin\Extensions;

use App\Models\Common\Media;
use Dcat\Admin\Support\Helper;
use Illuminate\Support\Facades\Log;

class UploadFilePro extends \Dcat\Admin\Form\Field\File
{
    protected $view = 'admin::form.file';

    public function __construct($column, $arguments = [])
    {
        parent::__construct($column, $arguments);

        $this->url('upload-file')->autoUpload();
    }

    protected function initialPreviewConfig()
    {
        $previews = [];
        Log::debug('initialPreviewConfig');

        foreach (Helper::array($this->value()) as $value) {
            Log::debug('value', [$value]);
            if(is_integer($value)) {
                $media = Media::find($value);
                if ($media) {
                    $previews[] = [
                        'id'   => $value,
                        'path' => $media->filename,
                        'url'  => $media->url,
                    ];
                }
            } else if($value) {
                $previews[] = [
                    'id'   => $value->id,
                    'path' => $value->filename,
                    'url'  => $value->url,
                ];
            }
        }

        return $previews;
    }

    protected function prepareInputValue($file)
    {
        return $file;
    }
}
